<template>
  <div class="role-container">
    <div class="search">
      <el-form style="text-align: left;margin-left: 10px;">
        <el-input v-model="key" size="small" placeholder="输入查询的角色名称" style="" auto-complete="off" style="width: 200px"></el-input>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search">搜索</el-button>
        <el-button size="small" native-type="reset" @click="searchReset" icon="el-icon-refresh">重置</el-button>
      </el-form>
      <div :span="1">
        <el-button type="warning" size="small" @click="isAddDialog = true" icon="el-icon-plus">添加</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      class="table-container">
      <el-table-column label="序号" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="role" label="角色标识" width="180"></el-table-column>
      <el-table-column prop="description" label="角色描述"></el-table-column>
      <el-table-column label="创建时间" width="220">
        <template slot-scope="scope">
          <span>{{ scope.row.createtime | unixTimeToDate('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <div style="text-align: center;display: flex;justify-content: space-around" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" plain size="small" :underline="false" @click="openEditorRole(scope.row.id)">编辑</el-button>
          <el-popconfirm confirmButtonText="确定" cancelButtonText="取消" icon="el-icon-warning-outline" iconColor="red" title="是否确定删除？"
                         @onConfirm="deleteRole(scope.row.id)" @onCancel="">
            <el-button type="danger" plain size="small" icon="el-icon-delete" :underline="false" slot="reference">删除</el-button>
          </el-popconfirm>
        </div>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="lay-pagination"
      layout="total, prev, pager, next, jumper"
      :current-page.sync="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 创建编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="isEditorDialog"
      width="40%">
      <el-form
        ref="editorRoleForm"
        :rules="roleRules"
        :model="editorRole"
        label-width="100px">
        <el-form-item label="角色标识" prop="role">
          <el-input v-model="editorRole.role" placeholder="请输入角色标识"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editorRole.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="editorRole.description" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限" prop="menuIds">
          <el-scrollbar wrap-style="overflow: auto;">
            <el-tree
              :data="selectMenuOptions"
              :props="defaultProps"
              show-checkbox
              check-strictly
              ref="tree"
              default-expand-all
              node-key="value"
              highlight-current
              @check-change="handleMenuCheckChange">
            </el-tree>
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditorRole">更新</el-button>
      </div>
    </el-dialog>

    <!-- 创建新增角色对话框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="isAddDialog"
      width="40%">
      <el-form
        ref="addRoleForm"
        :rules="roleRules"
        :model="addRole"
        label-width="100px">
        <el-form-item label="角色标识" prop="role">
          <el-input v-model="addRole.role" placeholder="请输入角色标识"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRole.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addRole.description" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-scrollbar wrap-style="overflow: auto;">
            <el-tree
              :data="selectMenuOptions"
              :props="defaultProps"
              show-checkbox
              check-strictly
              ref="tree"
              default-expand-all
              node-key="value"
              highlight-current
              @check-change="handleMenuCheckChange">
            </el-tree>
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getRoleList, getRoleById, insertRole, updateRoleById, deleteRoleById } from '@/api/role'
  import {getSelectMenu} from "../../api/menu";
    export default {
      name: "sysRole",
      data() {
        return {
          selectMenuOptions: [],
          defaultProps: {
            children: 'children',
            label: 'label'
          },
          key: '',
          loading: true,
          tableData: [
/*            {
              id: '10086',
              name: '管理员',
              role: 'ROLE_ADMIN',
              description: '管理一切',
              createtime: '2020/3/10 17:31:00'
            }*/
          ],
          pagination: {
            currentPage: 1,
            pageSize: 9,
            total: 1
          },
          isAddDialog: false,
          isEditorDialog: false,
          roleRules: {
            role: [{required: true, message: '请编辑角色标识', trigger: 'blur'}],
            name: [{required: true, message: '请编辑角色名称', trigger: 'blur'}],
            description: [{required: true, message: '请编辑角色描述', trigger: 'blur'}]
          },
          addRole: {
            role: '',
            name: '',
            description: '',
          },
          editorRole: {
            id: '',
            role: '',
            name: '',
            description: ''
          },
        }
      },
      methods: {
        //条件查询列表
        search() {
          this.getRoleList();
        },
        //重置条件查询
        searchReset() {
          this.key = ''
        },
        //添加角色
        submitAddRole() {
          this.$refs['addRoleForm'].validate(valid=>{
            if(valid) {
              let menuIds = this.$refs['tree'].getCheckedKeys().concat(this.$refs['tree'].getHalfCheckedKeys())
              this.editorRole.menuIds = menuIds
              insertRole(this.addRole).then(res=>{
                if(res.data.code === 200) {
                  this.$message.success('添加成功')
                  this.getRoleList()
                  this.$refs['addRoleForm'].resetFields()
                  this.isAddDialog = false
                }
              })
            }
          })
        },
        //更新角色
        submitEditorRole() {
          this.$refs['editorRoleForm'].validate(valid=>{
            if(valid) {
              let menuIds = this.$refs['tree'].getCheckedKeys().concat(this.$refs['tree'].getHalfCheckedKeys())
              this.editorRole.menuIds = menuIds
              updateRoleById(this.editorRole).then(res =>{
                if(res.data.code === 200) {
                  this.$message.success('更新成功')
                  this.isEditorDialog = false
                  this.getRoleList()
                }
              })
            }
          })
        },
        //删除指定角色
        deleteRole(id) {
          deleteRoleById(id).then(res=>{
            if(res.data.code === 200){
              this.$message.success('删除成功')
              this.getRoleList()
            }
          })
        },
        //节点选中状态发生变化时的回调
        handleMenuCheckChange(data, isCheck, node) {
          if(isCheck) { //当前节点被选中其父节点同样要被选中
            console.log(data)
            const parentId =  data.parentId;
            this.$refs['tree'].setChecked(parentId, true, false)
          }else { //当前节点未被选中则取消选中其下所有子节点
            if(data.children != null) {
              data.children.forEach(child =>{
                this.$refs['tree'].setChecked(child.value, false, false)
              })
            }
          }
        },
        //打开编辑角色面板初始化
        openEditorRole(id) {
          getRoleById(id).then(res =>{
            if(res.data.code === 200) {
              this.editorRole = res.data.data.role
              this.isEditorDialog = true
              this.$nextTick(()=>{
                this.$refs['tree'].setCheckedKeys(res.data.data.role.menuIds)
              })
            }
          })
        },
        //获取角色列表数据
        getRoleList() {
          let page = this.pagination.currentPage;
          getRoleList(page, this.key).then(res=>{
            if(res.data.code === 200) {
              this.loading = false
              let roleList = res.data.data.role_list;
              this.pagination.total = roleList.total;
              this.pagination.pageSize = roleList.pageSize;
              this.tableData = roleList.list;
            }
          })
        },
        //监听当前页码，并发起请求
        handleCurrentChange(page) {
          this.getRoleList()
        },
        //初始化菜单权限选择器
        initSelectMenu() {
          getSelectMenu().then(res=>{
            this.selectMenuOptions = res.data.data.select_menus
          })
        }
      },
      mounted() {
        this.getRoleList()
        this.initSelectMenu()
      }
    }
</script>

<style lang="scss" scoped>
  .role-container {
    background-color: #fff !important;
    min-height: 600px;
    padding: 10px;
    .search {
      display: flex;
      justify-content: space-between;
    }
    .table-container {
      width: 99%;
      margin: 10px;
    }
  }
  .el-scrollbar {
    height: 120px;
    border:1px rgba(29,29,29,0.15) solid;
    border-radius: 5px;
  }
</style>
